﻿using Microsoft.SharePoint;
using Microsoft.SharePoint.Workflow;
using Microsoft.SharePoint.WorkflowServices;
using ServBus.ListForm2013.Utility;
using System;
using System.Web;
using System.Web.UI;

namespace ServBus.ListForm2013.ControlTemplates.ListForm2013
{
    public partial class ListFormRedirect : UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                SPListItem item = SPContext.Current.ListItem;
                if (item != null)
                {
                    int listTemplateId = item.ParentList.BaseTemplate.GetHashCode();
                    if (listTemplateId == 107 || listTemplateId == 171)
                    {
                        //Response.Write("comin");
                        SPWeb web = item.Web;
                        string wfAssId = "";
                        string wInstanceId = "";
                        if (item.ContentTypeId.IsChildOf(Constants.WFTask_ContentType_Id))
                        {
                            wInstanceId = Convert.ToString(item["WF4InstanceId"]);
                            WorkflowServicesManager manager = new WorkflowServicesManager(web);
                            if (manager.IsConnected)
                            {
                                WorkflowInstanceService workflowInstanceService = manager.GetWorkflowInstanceService();
                                if (workflowInstanceService != null)
                                {
                                    WorkflowInstance workflowInstance = workflowInstanceService.GetInstance(new Guid(wInstanceId));
                                    wfAssId = Convert.ToString(workflowInstance.WorkflowSubscriptionId);
                                }
                            }
                        }
                        else
                        {
                            wInstanceId = Convert.ToString(item[SPBuiltInFieldId.WorkflowInstanceID]);
                            SPWorkflow spWF = new SPWorkflow(item, new Guid(wInstanceId));
                            wfAssId = Convert.ToString(spWF.AssociationId);

                        }
                        if (wfAssId != "")
                        {
                            SPList list = item.ParentList;
                            SPContentType cType = item.ContentType;

                            bool customizeFormEnabled = GetConfigItem(web, Convert.ToString(list.ID), Convert.ToString(cType.Id), wfAssId);
                            if (customizeFormEnabled)
                            {
                                string xsnLocation = web.Url + "/" + cType.ResourceFolder.Url + "/template-" + wfAssId + ".xsn";
                                SPFile file = web.GetFile(xsnLocation);
                                if (file.Exists)
                                {
                                    string listParameter = "listId=" + list.ID.ToString();
                                    string cTypeParameter = "ctypeId=" + cType.Id.ToString();
                                    string itemParameter = "itemId=" + item.ID.ToString();

                                    string redirectUrl = web.Url + "/" + cType.ResourceFolder.Url + "/edit_lb.aspx?" + listParameter + "&" + cTypeParameter + "&" + itemParameter;
                                    string sourceParameter = Page.Request["Source"];
                                    if (!string.IsNullOrEmpty(sourceParameter))
                                    {
                                        sourceParameter = HttpUtility.UrlEncode(sourceParameter);
                                        redirectUrl = redirectUrl + "&Source=" + sourceParameter;
                                    }
                                    Response.Redirect(redirectUrl);
                                }
                            }
                        }
                    }
                }
            }
            catch { }
        }

        private bool GetConfigItem(SPWeb web, string mListID, string mContentTypeID, string wfAssId)
        {
            bool customizeFormEnabled = false;
            if (string.IsNullOrEmpty(mListID) || string.IsNullOrEmpty(mContentTypeID)) return customizeFormEnabled;
            try
            {
                SPList configList = web.Lists[Constants.LookupForm_Config_NAME];
                SPQuery query = new SPQuery
                {
                    Query =
                              "<Where><And><And><Eq><FieldRef Name='Title' /><Value Type='Text'>" + mListID +
                              "</Value></Eq><Eq><FieldRef Name='mContentType' /><Value Type='Text'>" + mContentTypeID +
                              "</Value></Eq></And><Eq><FieldRef Name='wfAssId' /><Value Type='Text'>" + wfAssId +
                              "</Value></Eq></And></Where>"
                };
                SPListItemCollection items = configList.GetItems(query);
                if (items.Count > 0)
                {
                    if (Convert.ToString(items[0]["enabled"])=="1")
                    {
                        customizeFormEnabled = true;
                    }
                }
            }
            catch{}
            return customizeFormEnabled;
        }
    }
}
